<template>
  <div class="employees-container">
    <!-- 设置padding -->
    <div class="app-container">
      <!-- page-tools全局组件的引入 -->
      <page-tools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>

        <template #right>
          <el-button v-if="checkPermission('POINT_USER_IMPORT')" type="danger" size="small" @click="$router.push('/import?type=employee')">excel导入</el-button>
          <el-button v-if="checkPermission('POINT_USER_EXPORT')" type="success" size="small" @click="handleDownLoad">excel导出</el-button>
          <el-button type="primary" size="small" @click="clickAdd()"> + 新增员工</el-button>
        </template>
      </page-tools>

      <!-- 员工的表格 -->
      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" sortable="" width="80" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template #default="{row}">
              <!--
                1.有地址:   但地址没有用   staffPhoto:'http://wwww.sfsf.com/xxx.png'失效
                2.没有地址  staffPhoto:''
               -->
              <img
                v-imgerror="defaultImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                width="80px"
                @click="clickCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="" :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatTime('YYYY/MM/DD') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button :disabled="!checkPermission('POINT_USER_LOOK')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="clickAssignRole(row.id)">角色</el-button>
              <el-button :disabled="!checkPermission('POINT_USER_DELETE')" type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[3, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增员工组件弹出框 -->
      <add-employee
        :show-dialog.sync="showDialog"
        @add-employee="getEmployeeDetail"
      />

      <!-- 二维码弹出框 -->
      <el-dialog title="二维码" :visible="showCodeDialog" width="300px" @close="showCodeDialog = false">
        <div style="text-align:center;">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>

      <!-- 分配角色弹出框 -->
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

    </div>
  </div>
</template>

<script>
import QrCode from 'qrcode'
import dayjs from 'dayjs'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { reqGetEmployeeDetail, reqDelEmployee } from '@/api/employee'
import employeeObj from '@/constant/employees'
const hireType = employeeObj.hireType

// import hello from '@/mixins/hello'
import check from '@/mixins/check'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  mixins: [check],
  data() {
    return {
      title: '员工页',
      list: [],
      page: 1,
      size: 5,
      total: 0,

      loading: false,

      showDialog: false,

      defaultImg: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',

      showCodeDialog: false,

      showRoleDialog: false,

      userId: ''
    }
  },
  created() {
    // console.log('今天天气真热,烦死了')
    // console.log('今天天气真热,烦死了---员工业')
    this.getEmployeeDetail()
  },
  methods: {
    clickAdd() {
      if (!this.checkPermission('POINT_USER_ADD')) {
        this.$message.error('兄弟,你没有这个权限,请联系管理员')
        return
      }
      this.showDialog = true
    },

    // 获取员工详细列表
    async getEmployeeDetail() {
      this.loading = true

      const { data: { rows, total }} = await reqGetEmployeeDetail(this.page, this.size)
      this.list = rows
      this.total = total

      this.loading = false
    },
    // 每页显示条数改变时
    handleSizeChange(newSize) {
      this.size = newSize
      this.page = 1
      this.getEmployeeDetail()
    },
    // 页码值改变时
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeDetail()
    },
    // 处理表格的序号
    indexMethod(index) {
      // index是从0开始
      return index + 1 + (this.page - 1) * this.size
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // return 'hello vue'

      // 常量抽离:用单独模块存储常量数据
      // return cellValue === 1 ? '正式工' : '临时工'
      // cellValue = "1"  item = 1
      const res = hireType.find(item => item.id === +cellValue)

      return res ? res.value : '未知'
    },
    // 删除员工
    async del(id) {
      try {
        await this.$confirm('确定要删除该员工吗', '提示')
        await reqDelEmployee(id)
        this.$message.success('删除员工成功')

        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }

        this.getEmployeeDetail()
      } catch (err) {
        console.log(err)
      }
    },

    // excel导出功能
    async handleDownLoad() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      //  ['姓名', '主要信息', '      ', '       ', '       ', '    ', '部门']
      // 得到所有员工的数据
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { data: { rows }} = await reqGetEmployeeDetail(1, this.total)

      const resultArr = this.formatData(rows, headersRelations, headersArr)

      // webpack实现导入方法
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          // header就是导出excel的表头
          header: headersArr,
          // data导出excel的数据 ***结构必须是数组类型的二维数组 [[jack],[],[]]***
          data: resultArr,
          filename: '员工信息表', // 导出文件名
          autoWidth: true, // 自动适配宽度
          bookType: 'xlsx' // 文件的后缀名
        })
      })
    },
    formatData(rows, headersRelations, headersArr) {
      const resultArr = []

      rows.forEach(item => {
        const arr = []

        headersArr.forEach(o => {
          const enKey = headersRelations[o]
          let val = item[enKey]

          // 处理聘用形式格式
          if (enKey === 'formOfEmployment') {
            const obj = hireType.find(k => k.id === +val)
            val = obj ? obj.value : '未知'
          }

          // if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          //   val = dayjs(val).format('YYYY年MM月DD')
          // }
          // 处理时间格式
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            val = dayjs(val).format('YYYY年MM月DD')
          }

          arr.push(val)
        })

        resultArr.push(arr)
      })

      return resultArr
    },

    // 二维码
    clickCodeDialog(photoUrl) {
      if (!photoUrl) return

      this.showCodeDialog = true // 异步

      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, photoUrl)
      })
    },
    // 分配角色
    clickAssignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style>

</style>
